package com.lib.servlet.admin;

import com.alibaba.fastjson.JSON;
import com.lib.common.Constant;
import com.lib.entity.Admin;
import com.lib.entity.JsonResult;
import com.lib.service.AdminService;
import com.lib.service.ex.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "ChangePwdServlet", value = "/admin/ChangePwdServlet.do")
public class ChangePwdServlet extends HttpServlet {
    private AdminService adminService = new AdminService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Admin admin = (Admin) request.getSession().getAttribute(Constant.SESSION_ADMIN);
        String opwd = request.getParameter("opwd");
        String npwd = request.getParameter("npwd");
        String rpwd = request.getParameter("rpwd");
        System.out.println("------opwd="+opwd+"   npwd"+npwd+"   rpwd"+rpwd);
        JsonResult jsonResult = null;
        try {
            adminService.changePwd(admin.getName(),opwd,npwd,rpwd);
            jsonResult = JsonResult.getSuccessJR();
        } catch (UpdateServiceException e) {
            jsonResult = new JsonResult(Constant.JSON_STATE_EMPTY_ARGUMENT,e.getMessage());
        } catch (NotOldPwdException e) {
            jsonResult = new JsonResult(Constant.JSON_STATE_EMPTY_ARGUMENT,e.getMessage());
        } catch (RecordNotFoundException e) {
            jsonResult = new JsonResult(Constant.JSON_STATE_EMPTY_ARGUMENT,e.getMessage());
        } catch (InValidArgumentException e) {
            jsonResult = new JsonResult(Constant.JSON_STATE_INVALID_ARGUEMENT,e.getMessage());
        } catch (EmptyArgumentException e) {
            jsonResult = new JsonResult(Constant.JSON_STATE_EMPTY_ARGUMENT,e.getMessage());
        } catch (ServiceException e) {
            jsonResult = new JsonResult(Constant.JSON_STATE_EMPTY_ARGUMENT,e.getMessage());
        }

        System.out.println("------JsonResult");
        response.setCharacterEncoding("utf-8");
        response.getWriter().write(JSON.toJSONString(jsonResult));
        response.getWriter().flush();
        response.getWriter().close();
    }
}
